package com.guli.oss.service.serviceimpl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.guli.oss.service.FileService;
import com.guli.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        try{
//            创建oss实例
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            String s = UUID.randomUUID().toString().replaceAll("-", "");
            String filePath = s +  file.getOriginalFilename();
            filePath = new DateTime().toString("yyyy/MM/dd")+"/"+filePath;
            ossClient.putObject(bucketName,filePath ,inputStream);
            ossClient.shutdown();
            return "http://" + bucketName + "." + endPoint + "/" + filePath;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
